# -*- coding:utf-8 -*-
from flask import abort
from flask import json
from flask import render_template
from flask import request
from flask_login import login_required
from sqlalchemy import desc

from app.actions.category import category
from app.database.models import Category

__author__ = 'JiangW'


@category.route('/', methods=['GET'])
def category_list():
    query_dict = {
        'is_active': True,
    }

    page = request.args.get('page', 1, type=int)
    pagination = Category.query.filter_by(**query_dict).order_by(desc(Category.update_on)).paginate(
        page, per_page=20, error_out=False)
    return render_template('category/category_list.html', pagination=pagination)


@category.route('/edit', methods=['GET', 'POST'])
@login_required
def category_create():
    if request.method == 'GET':
        return render_template('category/category_edit.html')
    else:
        res = {'code': 1000}
        category_title = request.values.get('category_title')
        if category_title:
            Category(name=category_title).save()
        else:
            res['code'] = 1001
        return json.dumps(res)


@category.route('/edit/<int:category_id>', methods=['GET', 'POST'])
@login_required
def category_edit(category_id):
    current_category = Category.query.get(int(category_id))
    if current_category:
        if request.method == 'GET':
            return render_template('category/category_edit.html', current_category=current_category)
        else:
            res = {'code': 1000}
            category_title = request.values.get('category_title')
            if category_title:
                current_category.name = category_title
                current_category.save()
            else:
                res['code'] = 1001
            return json.dumps(res)
    else:
        return abort(404)


@category.route('/delete/<int:category_id>', methods=['GET', 'POST'])
@login_required
def category_delete(category_id):
    current_category = Category.query.get(int(category_id))
    if current_category:
        if request.method == 'GET':
            return render_template('category/category_delete.html', current_category=current_category)
        else:
            res = {'code': 1000}
            current_category.delete()
            return json.dumps(res)
    else:
        return abort(404)